package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JingHuShenUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import io.lettuce.core.ScriptOutputType;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 京沪深
 */
@Service
public class JingHuShenApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();


    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String mobileMd5 = memberSourceInfo.getMobileMd5();
        String queryUrl = pushApiKeyParam.getCheckUrl();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", mobileMd5);
        paramMap.put("channelCode", pushApiKeyParam.getApiCode());


        log.info("【京沪深】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【京沪深】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneno", memberSourceInfo.getMobile());
        bizMap.put("custname", memberSourceInfo.getRealname());
        bizMap.put("city", city);
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("loan_amount", JingHuShenUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("have_car", JingHuShenUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("have_house", JingHuShenUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("have_fund", JingHuShenUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("have_insurance", JingHuShenUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("have_warranty", JingHuShenUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("have_job", 1);
        bizMap.put("have_bankcard", 1);
        bizMap.put("have_creditcard", JingHuShenUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("qudaosource", "臻享分期");
        bizMap.put("source", "通e贷");
        bizMap.put("loanpurpose", BaseTypeInfoEnum.Yongtu.getNameByValue(memberSourceInfo.getYongtu()));


        long time = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(time);
        String timestamp = sdf.format(date);


        // 要加密的数据
        String data = JSON.toJSONString(bizMap);


        String encryptData = encryptData(data, pushApiKeyParam.getApiSecret(), pushApiKeyParam.getPriKey());


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("merchantno", pushApiKeyParam.getApiKey());
        paramMap.put("timestamp", timestamp);
        paramMap.put("data", encryptData);


        log.info("【京沪深】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【京沪深】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String dealStatus = resultObject.getString("dealStatus");
        String dealDesc = resultObject.getString("dealDesc");

        pushApiResult.setCode(dealStatus);
        pushApiResult.setMessage(dealDesc);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(dealStatus), "0000")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


    public static String encryptData(String jsonData, String apiSecret, String priKey) throws Exception {
        // 设置密钥
        byte[] keyBytes = apiSecret.getBytes(); // 使用前24字节作为密钥
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");

        // 设置偏移量
        byte[] ivBytes = priKey.getBytes();
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        // 设置加密算法、模式和填充方式
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        // 要加密的数据
        byte[] dataBytes = jsonData.getBytes("UTF-8");
        byte[] encryptedBytes = cipher.doFinal(dataBytes);

        // 对加密后的数据进行Base64编码
        String encryptedData = Base64.getEncoder().encodeToString(encryptedBytes);

        return encryptedData;
    }


//    public static void main(String[] args) throws Exception {
//        // 设置密钥
//        byte[] keyBytes = "32e326b5053bc97b895f2c14".getBytes(); // 使用前24字节作为密钥
//        SecretKey key = new SecretKeySpec(keyBytes, "DESede");
//
//        // 设置偏移量
//        byte[] ivBytes = "01234567".getBytes();
//        IvParameterSpec iv = new IvParameterSpec(ivBytes);
//
//        // 设置加密算法、模式和填充方式
//        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
//        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
//
//        // 要加密的数据
//        String data = "要加密的数据";
//        byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));
//
//        // 对加密后的数据进行Base64编码
//        String encryptedData = Base64.getEncoder().encodeToString(encryptedBytes);
//
//        // 输出加密结果
//        System.out.println("加密后的数据：" + encryptedData);
//
//        // 解密过程
//        cipher.init(Cipher.DECRYPT_MODE, key, iv);
//        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
//
//        // 解密后的数据
//        String decryptedData = new String(decryptedBytes, "UTF-8");
//
//        // 输出解密结果
//        System.out.println("解密后的数据：" + decryptedData);
//    }




}
